class CoursesController < ApplicationController

  before_action :student_logged_in, only: [:select, :quit, :list, :hint]
  before_action :teacher_logged_in, only: [:new, :create, :edit, :destroy, :update, :open, :close]#add open by qiao
  before_action :logged_in, only: :index

  #-------------------------for teachers----------------------

  def new
    @course=Course.new
  end

  def create
    @course = Course.new(course_params)
    if @course.save
      current_user.teaching_courses<<@course
      redirect_to courses_path, flash: {success: "新课程申请成功"}
    else
      flash[:warning] = "信息填写有误,请重试"
      render 'new'
    end
  end

  def edit
    @course=Course.find_by_id(params[:id])
  end

  def update
    @course = Course.find_by_id(params[:id])
    if @course.update_attributes(course_params)
      flash={:info => "更新成功"}
    else
      flash={:warning => "更新失败"}
    end
    redirect_to courses_path, flash: flash
  end

  def open
    @course=Course.find_by_id(params[:id])
    @course.update_attributes(open: true)
    redirect_to courses_path, flash: {:success => "已经成功开启该课程:#{ @course.name}"}
  end

  def close
    @course=Course.find_by_id(params[:id])
    @course.update_attributes(open: false)
    redirect_to courses_path, flash: {:success => "已经成功关闭该课程:#{ @course.name}"}
  end

  def destroy
    @course=Course.find_by_id(params[:id])
    current_user.teaching_courses.delete(@course)
    @course.destroy
    flash={:success => "成功删除课程: #{@course.name}"}
    redirect_to courses_path, flash: flash
  end

  #-------------------------for students----------------------
  
  def list
    excluded_courses_id = [-1]
    current_user.courses.each do |course|
      excluded_courses_id << course.id
    end
    @courses = Course.where("open = true and id not in (?)", excluded_courses_id).paginate(page: params[:page], per_page: 4)
    if params.has_key?(:course_time)
      ctime = params[:course_time]
      ctype = params[:course_type]
      cname = params[:course_name]
      conditions = "open = true and id not in (?)"
      if ctime != "不限"
        conditions += " and course_time like '%#{ctime}%'"
      end
      if ctype != "不限"
        conditions += " and course_type = '#{ctype}'"
      end
      if cname != ""
        conditions += " and name like '%#{cname}%'"
      end
      @courses = Course.where(conditions, excluded_courses_id).paginate(page: params[:page], per_page: 4)
    end
  end

 def select
    @course=Course.find_by_id(params[:id])
    if @course.student_num >= @course.limit_num
      flash={:danger => "选课人数已满: #{@course.name}"}
      redirect_to list_courses_path, flash: flash
    else
      conflict = 0
      conflict_name = ""
      current_user.courses.each do |course|
        day = course.course_time[0...2]
        start = (course.course_time.match(/(\d+)-(\d+)/))[1].to_i
        ending = (course.course_time.match(/(\d+)-(\d+)/))[2].to_i
        newday = @course.course_time[0...2]
        newstart = (@course.course_time.match(/(\d+)-(\d+)/))[1].to_i
        newending = (@course.course_time.match(/(\d+)-(\d+)/))[2].to_i
        if day == newday && start <= newstart && ending >= newstart
          conflict = 1
          conflict_name = course.name
          break
        end
        if day == newday && start <= newending && ending >= newending
          conflict = 1
          conflict_name = course.name
          break
        end
      end
      if conflict == 0
        current_user.courses<<@course
        @course.student_num += 1
        @course.save
        flash={:suceess => "成功选择课程: #{@course.name}"}
        redirect_to courses_path, flash: flash
      else
        flash={:danger => "课程: #{conflict_name}和课程: #{@course.name}的上课时间冲突"}
        redirect_to list_courses_path, flash: flash
      end
    end
  end

  def quit
    @course=Course.find_by_id(params[:id])
    current_user.courses.delete(@course)
    @course.student_num -= 1
    @course.save
    flash={:success => "成功退选课程: #{@course.name}"}
    redirect_to courses_path, flash: flash
  end

  def hint
    @public_courses = []
    @fstlevel_courses = []
    @major_courses = []
    @public_credit = 0.0
    @fstlevel_credit = 0.0
    @major_credit = 0.0
    @total_credit = 0.0
    current_user.courses.each do |course|
      case course.course_type
      when "公共选修课"
        @public_courses << course
        @public_credit += (course.credit.match(/(\d+)\.(\d+)/))[0].to_f
      when "一级学科核心课", "一级学科普及课"
        @fstlevel_courses << course
        @fstlevel_credit += (course.credit.match(/(\d+)\.(\d+)/))[0].to_f
      when "专业普及课", "专业核心课", "专业研讨课"
        @major_courses << course
        @major_credit += (course.credit.match(/(\d+)\.(\d+)/))[0].to_f
      end
      @total_credit += (course.credit.match(/(\d+)\.(\d+)/))[0].to_f
    end
  end

  def table
    @courses_table = Hash.new("")
    current_user.courses.each do |course|
      day = course.course_time[0...2]
      start = (course.course_time.match(/(\d+)-(\d+)/))[1].to_i
      ending = (course.course_time.match(/(\d+)-(\d+)/))[2].to_i + 1
      for i in start...ending
        @courses_table[day + i.to_s] = course.name
      end
    end
  end


  #-------------------------for both teachers and students----------------------

  def index
    @course=current_user.teaching_courses.paginate(page: params[:page], per_page: 4) if teacher_logged_in?
    @course=current_user.courses.paginate(page: params[:page], per_page: 4) if student_logged_in?
  end


  private

  # Confirms a student logged-in user.
  def student_logged_in
    unless student_logged_in?
      redirect_to root_url, flash: {danger: '请登陆'}
    end
  end

  # Confirms a teacher logged-in user.
  def teacher_logged_in
    unless teacher_logged_in?
      redirect_to root_url, flash: {danger: '请登陆'}
    end
  end

  # Confirms a  logged-in user.
  def logged_in
    unless logged_in?
      redirect_to root_url, flash: {danger: '请登陆'}
    end
  end

  def course_params
    params.require(:course).permit(:course_code, :name, :course_type, :teaching_type, :exam_type,
                                   :credit, :limit_num, :class_room, :course_time, :course_week)
  end


end
